<script setup lang="ts">
//引入组件
import { ref } from 'vue';
import { onLoad } from '@dcloudio/uni-app';
import CustomNavbar from './components/CustomNavbar.vue';
import CategoryPanel from './components/CategoryPanel.vue';
import HotPanel from './components/HotPanel.vue';
import { getHomeBannerAPI,getHomeCategoryAPI,getHomeHotAPI } from '@/services/home'
import type { BannerItem,CategoryItem,HotItem } from '@/types/home';
import type { XtxGuessInstance } from '@/types/components';
import PageSkeleton from './components/PageSkeleton.vue'

const bannerList = ref<BannerItem[]>([])
const categoryList = ref<CategoryItem[]>([])
const hotList = ref<HotItem[]>([])
const guessRef = ref<XtxGuessInstance>()
const isTriggered = ref(false)
const isLoading = ref(false) // 是否加载中标记

const getHomeBannerData = async () => {
  const res = await getHomeBannerAPI()
  bannerList.value = res.result
}
const getHomeCategoryData = async () => {
  const res = await getHomeCategoryAPI()
  categoryList.value = res.result
}
const getHomeHotData = async () => {
  const res = await getHomeHotAPI()
  hotList.value = res.result
}
// 页面加载时
onLoad(async _ => {
  isLoading.value = true
  // 获取数据
  await Promise.all([
    getHomeBannerData(),
    getHomeCategoryData(),
    getHomeHotData()
  ])
  isLoading.value = false
})
//页面滚动触底
const onScrolltolower = () => {
  guessRef.value?.getMore()
}
//页面下拉效果
const onRefresherrefresh = async () => {
  isTriggered.value = true
  //清空重置猜你喜欢的数据
  guessRef.value?.resetData()
  await Promise.all([
    getHomeBannerData(),
    getHomeCategoryData(),
    getHomeHotData(),
    //猜你喜欢
    guessRef.value?.getMore()
  ])
  //关闭动画
  isTriggered.value = false
}
</script>

<template>
  <!-- 自定义导航栏 -->
  <CustomNavbar></CustomNavbar>
  <scroll-view
    scroll-y
    refresher-enabled
    :refresher-triggered="isTriggered"
    @refresherrefresh="onRefresherrefresh"
    @scrolltolower="onScrolltolower"
  >
    <PageSkeleton v-if="isLoading"></PageSkeleton>
    <template v-else>
      <!-- 轮播图 -->
      <XtxSwiper :list="bannerList"/>
      <!-- 宫格分类 -->
      <CategoryPanel :list="categoryList"></CategoryPanel>
      <!-- 热门商品 -->
      <HotPanel :list="hotList"/>
      <!-- 猜你喜欢 -->
      <XtxGuess ref="guessRef"></XtxGuess>
    </template>
  </scroll-view>
</template>

<style lang="scss">
page{
  background-color: #f7f7ff;
  height: 100%;
  display: flex;
  flex-direction: column;
}
</style>
